package com.runen.wnhz.runen.ui.fragment.major;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.UserMessageBean;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.ui.OnItemClickListener;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.activity.major.MessageDetailActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.UserMessageRecyclerAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class UserMessageFragment extends Fragment {

    @BindView(R.id.user_message_recycler)
    RecyclerView userMessageRecycler;
    Unbinder unbinder;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;
    private View view;
    private String token;
    private int currentPage = 0;
    private boolean hasNextPage = false;
    private int totalPage = 0;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;

    private UserMessageRecyclerAdapter adapter;

    private List<UserMessageBean.DataBean.ListBean> listBeans;

    private int position;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = View.inflate(getActivity(), R.layout.user_message_layout, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListener();
        initData();
        setUserVisibleHint(true);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getUserVisibleHint() && getActivity() != null){
            getUserMessage(String.valueOf(currentPage));
        }
    }

    private void setListener(){
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if(hasNextPage) {
                    currentPage = currentPage + 1;
                    isLoadMore = true;
                    getUserMessage(String.valueOf(String.valueOf(currentPage)));
                }else{
                    ToastUtil.showToast("暂无更多数据");
                }
                smartRefreshLayout.finishLoadMore(true);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                 currentPage = 0;
                 isRefresh = true;
                 getUserMessage(String.valueOf(currentPage));
                 smartRefreshLayout.finishRefresh(true);
            }
        });
    }

    private void initData() {
        listBeans = new ArrayList<>();
        userMessageRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
       userMessageRecycler.addItemDecoration( new HorizontalDividerItemDecoration.Builder(getActivity())
               .color(Color.parseColor("#888888"))
               .sizeResId(R.dimen.view_height)
               .build());
        ACacheUtlis cacheUtlis = ACacheUtlis.getInstance();
        if (cacheUtlis != null) {
            UserBean reqeustUser = cacheUtlis.getReqeustUser(getActivity());
            if (reqeustUser != null) {
                token = reqeustUser.getToken();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0 && resultCode == Activity.RESULT_OK){
            int tempCurrentPage = 0;
            isRefresh = true;
            getUserMessage(String.valueOf(tempCurrentPage));
        }
    }

    private void getUserMessage(String pageNum) {
        if (token != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("type", "1").add("page", pageNum).build();
            final Request request = new Request.Builder().url(NetUtils.USER_MESSAGE_CENTER).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("消息数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    handleUserMessageData(response);
                }
            });
        }
    }

    private void handleUserMessageData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            final String json = responseBody.string();
            System.out.println("jsonnnn == " + json);
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UserMessageBean userMessageBean = new Gson().fromJson(json, UserMessageBean.class);
                        if ("1".equals(userMessageBean.getRe())) {
                            UserMessageBean.DataBean dataBean = userMessageBean.getData();
                            if (dataBean != null) {
                                if ("1".equals(dataBean.getIs_page())) {
                                    hasNextPage = true;
                                } else {
                                    hasNextPage = false;
                                }
                                currentPage = Integer.parseInt(dataBean.getPage());
                                if (isRefresh) {
                                    if (listBeans.size() != 0) {
                                        listBeans.clear();
                                    }
                                    listBeans.addAll(dataBean.getList());
                                    if (adapter == null) {
                                        adapter = new UserMessageRecyclerAdapter(getActivity(), listBeans);
                                        adapter.setOnItemClickListener(new OnItemClickListener() {
                                            @Override
                                            public void onItemClick(View view, int postion) {
                                                UserMessageFragment.this.position = postion;
                                                UserMessageBean.DataBean.ListBean listBean = listBeans.get(postion);
                                                Intent intent = new Intent(getActivity(), MessageDetailActivity.class);
                                                intent.putExtra("id", listBean.getId());
                                                startActivityForResult(intent, 0);
                                            }
                                        });
                                        userMessageRecycler.setAdapter(adapter);
                                    } else {
                                        adapter.notifyDataSetChanged();
                                    }
                                    isRefresh = false;
                                    return;
                                }
                                if (isLoadMore) {
                                    listBeans.addAll(dataBean.getList());
                                    if (adapter == null) {
                                        adapter = new UserMessageRecyclerAdapter(getActivity(), listBeans);
                                        adapter.setOnItemClickListener(new OnItemClickListener() {
                                            @Override
                                            public void onItemClick(View view, int postion) {
                                                UserMessageFragment.this.position = postion;
                                                UserMessageBean.DataBean.ListBean listBean = listBeans.get(postion);
                                                Intent intent = new Intent(getActivity(), MessageDetailActivity.class);
                                                intent.putExtra("id", listBean.getId());
                                                startActivityForResult(intent, 0);
                                            }
                                        });
                                        userMessageRecycler.setAdapter(adapter);
                                    } else {
                                        adapter.notifyDataSetChanged();
                                    }
                                    isLoadMore = false;
                                    return;
                                }
                                currentPage = 0;
                                if (listBeans.size() != 0) {
                                    listBeans.clear();
                                }
                                listBeans.addAll(dataBean.getList());
                                adapter = new UserMessageRecyclerAdapter(getActivity(), listBeans);
                                adapter.setOnItemClickListener(new OnItemClickListener() {
                                    @Override
                                    public void onItemClick(View view, int postion) {
                                        UserMessageFragment.this.position = postion;
                                        UserMessageBean.DataBean.ListBean listBean = listBeans.get(postion);
                                        Intent intent = new Intent(getActivity(), MessageDetailActivity.class);
                                        intent.putExtra("id", listBean.getId());
                                        startActivityForResult(intent, 0);
                                    }
                                });
                                userMessageRecycler.setAdapter(adapter);
                            }
                        } else if ("0".equals(userMessageBean.getRe())) {
                            ToastUtil.showToast(userMessageBean.getInfo());
                        } else if ("-1".equals(userMessageBean.getRe())) {
                            ToastUtil.showToast(userMessageBean.getInfo());
                            startActivity(new Intent(getActivity(), LoginForPersonalActivity.class));
                        }
                    }
                });
            }
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
